<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/5/21
 * Time: 16:39
 */

namespace app\api\model;


use think\Exception;

class Coupon extends BaseModel
{
    protected $append = ['start_time_date', 'end_time_date'];

    /**
     * 格式化活动开始时间
     * @param $value
     * @param $data
     * @return false|string
     */
    public function getStartTimeDateAttr($value, $data) {
        return date('Y-m-d H:i:s', $data['start_time']);
    }

    /**
     * 格式化活动结束时间
     * @param $value
     * @param $data
     * @return false|string
     */
    public function getEndTimeDateAttr($value, $data) {
        return date('Y-m-d H:i:s', $data['end_time']);
    }

    /**
     * 写入数据库前转成时间戳
     * @param $value
     * @return false|int
     */
    public function setStartTimeAttr($value) {
        return strtotime($value);
    }

    /**
     * 写入数据库前转成时间戳
     * @param $value
     * @return false|int
     */
    public function setEndTimeAttr($value) {
        return strtotime($value);
    }

    /**
     * 获取优惠券列表
     * @param array $where
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($where = []) {
        return self::where($where)
            ->order('id desc')
            ->paginate(input('param.limit', 15), false, ['query' => input('param.')]);
    }

    /**
     * 创建或者编辑优惠券
     * @param $param
     * @param $id
     * @return array|\think\response\Json
     */
    public static function createOrUpdateCoupon($param, $id) {

        try {
            if ($id > 0) {

                $coupon = self::get($id);
                if (!$coupon) {
                    return json(['code' => 1, 'msg' => '优惠券不存在']);
                }

                $check_name = self::where([['name', 'eq', $param['name']], ['id', 'neq', $id]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '优惠券名称已存在!'];
                }

                $coupon->save($param);

            } else {
                $check_name = self::where([['name', 'eq', $param['name']]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '优惠券名称已存在!'];
                }

                self::create($param);
            }
            return ['code' => 0, 'msg' => '保存成功'];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }
}